package com.guide.hello.socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.concurrent.*;

public class HelloClient {
    private static final Logger logger = LoggerFactory.getLogger(HelloClient.class);

    public Object send(Socket socket, Message message) {
        try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
             ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream())) {
            objectOutputStream.writeObject(message);
            objectOutputStream.flush();
            return objectInputStream.readObject();
        } catch (IOException e) {
            logger.info("An error has occurred when reading or writing an object.");
        } catch (ClassNotFoundException e) {
            logger.info("The class called Message has not been found!");
        }
        return null;
    }

    public static void main(String[] args) {
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        String host = "127.0.0.1";
        int port = 6666;
        try (ExecutorService threadPool = new ThreadPoolExecutor(100, 1000, 1, TimeUnit.MINUTES, new ArrayBlockingQueue<>(1000), threadFactory);) {
            while (true) {
                try (Socket socket = new Socket(host, port)) {
                    HelloClient helloClient = new HelloClient();
                    Message message = new Message("This is a message from client.");
                    message = (Message) helloClient.send(socket, message);
                    logger.info(message.getContent());
                } catch (IOException e) {
                    logger.info("An error has occurred when creating the socket.");
                }
            }
        }

    }
}
